﻿#region Apache 2.0 License Information
// Copyright 2009 Jon Fuller
//
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
#endregion

using System;
using System.ComponentModel;
using System.Linq.Expressions;
using System.Reflection;

namespace CoreLib
{
    public class NotifyPropertyChanged : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        protected void SetProperty<T>( Expression<Func<T>> propExpr, Expression<Func<T>> fieldExpr, T value )
        {
            SetProperty( propExpr, fieldExpr, value, () => { } );
        }

        protected void SetProperty<T>( Expression<Func<T>> propExpr, Expression<Func<T>> fieldExpr, T value, Action doIfChanged )
        {
            var prop = (PropertyInfo)((MemberExpression)propExpr.Body).Member;
            var field = (FieldInfo)((MemberExpression)fieldExpr.Body).Member;

            var currVal = prop.GetValue( this, null );

            if( currVal == null && value == null )
                return;
            if( currVal == null || !currVal.Equals( value ) )
            {
                field.SetValue( this, value );
                doIfChanged();

                if( PropertyChanged != null )
                    PropertyChanged( this, new PropertyChangedEventArgs( prop.Name ) );
            }
        }
    }
}
